/*
 * @Author: Wangjun
 * @Date: 2023-03-14 15:11:56
 * @LastEditTime: 2023-12-16 16:33:01
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \xr_node_calc\models\setup.go
 * hnxr
 */
package models

import (
	"errors"
	"fmt"
	"os"
	"time"

	"gitee.com/haodreams/golib/easyurl"
	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/libs/config"
	"gitee.com/haodreams/libs/ee"
	"gitee.com/haodreams/libs/routine"
	"gitee.com/hnxr_1/nodex"
	"gitee.com/hnxr_1/nodex/nodeconv"
	jsoniter "github.com/json-iterator/go"
)

var boss *Boss
var json = jsoniter.ConfigCompatibleWithStandardLibrary

func Setup() (err error) {
	kind := config.DefaultInt("kind", 1)
	if kind == 86 {
		data := nodex.RegData()
		os.WriteFile("data/buildin.json", data, 0644)
		nodeconv.MakeNodes("data/buildin.json", "data/nodes.json")
		url := config.String("node.register")
		if url != "" {
			nodes := nodex.GetNodeList()
			for _, node := range nodes {
				data := node.RegData()
				_, _, err := easyurl.JSON(url, data)
				if err != nil {
					logs.Warn(url, err)
				}
			}
		}
	} else {
		nodeconv.MakeNodes("data/xrnodes.json", "data/nodes.json")
		return
	}

	boss = new(Boss)
	err = boss.Setup()
	if err != nil {
		return ee.Print(err, logs.CbWarn)
	}

	go Loop()
	return
}

func Loop() {
	for routine.IsRunning() {
		boss.Loop()
		if routine.IsRunning() {
			time.Sleep(time.Second)
		}
	}
}

/**
 * @description: 去掉中的\"
 * @param {string} str
 * @return {*}
 */
func ToString(str string) string {
	s := []byte(str)
	n := len(s)
	data := make([]byte, n)
	idx := 0
	for i := 0; i < n; i++ {
		v := s[i]
		if v == '\\' {
			if i+1 < n {
				if s[i+1] == '"' {
					data[idx] = '"'
					i++
					continue
				}
			}
		}
		data[idx] = v
		idx++
	}
	return string(data[:idx])
}

func Release(data []byte) (err error) {
	//err = errors.New("功能开发中")
	//1 验证画布正确性
	p := new(nodex.Task)
	err = json.Unmarshal(data, p)
	if err != nil {
		return ee.Print(err, logs.CbWarn)
	}

	if p.FileName == "" {
		return errors.New("画布文件名不正确")
	}

	_, _, err = p.ToNodes()
	if err != nil {
		return ee.Print(err, logs.CbWarn)
	}

	// if p.Attrib == "" {
	// 	return errors.New("画布丢失关联属性")
	// }

	// kv := map[string]string{}
	// err = json.Unmarshal([]byte(ToString(p.Attrib)), &kv)
	// if err != nil {
	// 	return ee.Print(err, logs.CbWarn)
	// }

	// //查看配置的维度是否正确
	//category := kv["category"]
	// if category != "model" {
	// 	dim := GetBoss().mapDim[category]
	// 	if dim == nil {
	// 		return errors.New("画布维度不正确")
	// 	}
	// }
	path := NodePath + "openplant/"
	// easy.MkdirAll(path)
	// parent := kv["parent"]
	// if parent != "" {
	// 	path += "/" + parent + "/"
	// } else {
	// 	path += "/"
	// }

	path += p.FileName + ".json"
	err = os.WriteFile(path, data, 0644)
	logs.Info("画布发布:", path)

	return
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func GetBoss() *Boss {
	return boss
}

/**
 * @description: 获取任务列表
 * @param {int} id
 * @param {string} category
 * @return {*}
 */
func GetTaskList(id int, category string) []*Task {
	return boss.GetTaskList(id, category)
}

/**
 * @description: 获取画布参数数据
 * @param {*} path
 * @param {string} category
 * @param {int} devid
 * @return {*}
 */
func GetTaskData(path, category string, devid int) (data any, err error) {
	if boss == nil {
		return
	}
	return // boss.GetTaskData(path, category, devid)
}

func MapToIDs(mp map[int]bool) (ids []int) {
	ids = make([]int, 0, len(mp))
	for id := range mp {
		ids = append(ids, id)
	}
	return
}

func MapToStrs(mp map[string]bool) (ss []string) {
	ss = make([]string, 0, len(mp))
	for id := range mp {
		ss = append(ss, id)
	}
	return
}

// MakeKey 生成规则 场站ID+机型ID
func MakeKey(plantID, modelID int) string {
	return fmt.Sprintf("%d_%d", plantID, modelID)
}
